<?php

namespace app\controller\v1;

use app\controller\CommonController;
use app\validate\v1\Image as ImageValid;
use think\facade\Config;
use think\facade\Filesystem;
use think\facade\Request;

class Upload extends CommonController
{
    /**
     * 单张图
     * @return \think\response\Json
     */
    public function single(): \think\response\Json
    {
        $file = Request::file('file');
        $dir = Request::post('dir', 'tmp');
        validate(ImageValid::class)->check(['image' => $file]);

        // 指定上传到public目录下
        $savePath = Filesystem::disk('public')->putFile($dir, $file);
        $savePath = str_replace('\\', '/', $savePath);

        return $this->responseInfo([
            'url' => Config::get('app.app_host') . '/storage/' . $savePath
        ]);
    }

    /**
     * 多张图
     * @return \think\response\Json
     */
    public function multiple(): \think\response\Json
    {
        $files = Request::file('files');
        $dir = Request::post('dir', 'tmp');

        // 循环验证
        foreach ($files as $file) {
            validate(ImageValid::class)->check(['image' => $file]);
        }

        // 循环上传
        $filePath = [];
        foreach ($files as $key => $file) {
            $savePath = Filesystem::disk('public')->putFile($dir, $file);
            $savePath = str_replace('\\', '/', $savePath);
            $filePath[$key] = Config::get('app.app_host') . '/storage/' . $savePath;
        }

        return $this->responseData($filePath);
    }

}